home *** CD-ROM | disk | FTP | other *** search
/ Cream of the Crop 26 / Cream of the Crop 26.iso / program / ddj0897.zip / RCSC.ZIP / DEMO51 / PHILOS.C < prev    next >
C/C++ Source or Header  |  1997-01-12  |  1KB  |  78 lines

  1. #include <stdio.h>
  2.  
  3. unsigned int seed = 127;
  4.  
  5. /* generate pseudo-random number between 1-200 inclusive */
  6. rnd()
  7. {
  8.  
  9.     seed *= 177;
  10.     if (!seed)
  11.         seed = 127;
  12.     return seed % 200 + 1;
  13. }
  14.  
  15. /* logic for a dining philosopher */
  16. void philosopher(id)
  17. int id;
  18. {
  19.     char buffer[128];
  20.     int n;
  21.  
  22.     while (1)
  23.     {
  24.         /* acquire chopsticks */
  25.         GetChopsticks(id);
  26.  
  27.         /* display message and eat */
  28.         n = rnd();
  29.             sprintf(buffer, "Philosopher #%d eating for %d ticks :-)\n", 
  30.             id, n);
  31.         Send(buffer);    /* pass to console task */
  32.         Delay(n);    /* simulate eating */
  33.  
  34.         /* release chopsticks */
  35.         PutChopsticks(id);
  36.  
  37.         /* display message and think */
  38.         n = rnd();
  39.             sprintf(buffer, "Philosopher #%d thinking for %d ticks :-(\n", 
  40.             id, n);
  41.         Send(buffer);    /* pass to console task */
  42.         Delay(n);    /* simulate thinking */
  43.     }
  44. }
  45.  
  46. /* task declarations */
  47. void task p0()
  48. {
  49.     philosopher(0);
  50. }
  51.  
  52. void task p1()
  53. {
  54.     philosopher(1);
  55. }
  56.  
  57. void task p2()
  58. {
  59.     philosopher(2);
  60. }
  61.  
  62. void task p3()
  63. {
  64.     philosopher(3);
  65. }
  66.  
  67. /* main program: note that the function philosopher is used as
  68.     the body of a number of tasks including main() */
  69. main()
  70. {
  71.     /* all declared tasks start before this. main() is converted
  72.         into a task by Concurrent Small C and becomes the
  73.         fifth philosopher */
  74.     philosopher(4);
  75.  
  76. }
  77.  
  78.